import { defineStore } from 'pinia'
import { ref, watch } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 从本地存储加载状态
  const token = ref(localStorage.getItem('token') || '');
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || 'null'));
  
  // 从本地存储加载会员信息
  const savedMembershipInfo = localStorage.getItem('membershipInfo');
  const membershipInfo = ref(
    savedMembershipInfo 
      ? JSON.parse(savedMembershipInfo) 
      : {
          packageType: '无套餐',
          remainingQuota: 0,
          remainingDays: 0,
        }
  );
  
  const isAuthenticated = ref(!!token.value);
  
  // 使用watch监听membershipInfo变化，自动保存到localStorage
  watch(
    membershipInfo, 
    (newValue) => {
      localStorage.setItem('membershipInfo', JSON.stringify(newValue));
      // 触发自定义事件，便于组件监听
      window.dispatchEvent(new CustomEvent('membershipUpdated', { detail: newValue }));
    },
    { deep: true }
  );

  // 监听token变化，自动更新isAuthenticated状态
  watch(token, (newToken) => {
    isAuthenticated.value = !!newToken;
  });

  const login = (newToken, userData) => {
    token.value = newToken;
    // userData可能是字符串（phone）或对象（完整的userInfo）
    if (typeof userData === 'string') {
      // 兼容旧代码：如果只传递了phone，创建一个对象
      userInfo.value = { phone: userData };
    } else {
      // 新代码：传递完整的userInfo对象
      userInfo.value = userData;
    }
    isAuthenticated.value = true;
    localStorage.setItem('token', newToken);
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value));
  };

  const updateMembership = (data) => {
    membershipInfo.value = { ...membershipInfo.value, ...data };
    // 不需要手动保存到localStorage，watch会自动处理
  };

  const logout = () => {
    console.log('执行登出操作...');
  
    // 清除状态
    token.value = '';
    userInfo.value = null;
    membershipInfo.value = { packageType: '无套餐', remainingQuota: 0, remainingDays: 0 };
    isAuthenticated.value = false;
  
    // 清空 localStorage
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
    localStorage.removeItem('membershipInfo'); // 也清除会员信息
    localStorage.removeItem('adPopupMinimized'); // 清除广告最小化状态
  };

  const restoreAuth = () => {
    const savedToken = localStorage.getItem('token');
    if (savedToken) {
      token.value = savedToken;
      isAuthenticated.value = true;
      
      // 恢复用户信息
      const savedUserInfo = localStorage.getItem('userInfo');
      if (savedUserInfo) {
        userInfo.value = JSON.parse(savedUserInfo);
      }
      
      // 恢复会员信息
      const savedMembershipInfo = localStorage.getItem('membershipInfo');
      if (savedMembershipInfo) {
        membershipInfo.value = JSON.parse(savedMembershipInfo);
      }
    }
  };

  return { token, userInfo, membershipInfo, isAuthenticated, login, updateMembership, logout, restoreAuth };
});